package com.graduation.smartparkingplatform.Controller;

import com.graduation.smartparkingplatform.Pojo.User;
import com.graduation.smartparkingplatform.Repository.CaptchaRepository;
import com.graduation.smartparkingplatform.Response.Response;
import com.graduation.smartparkingplatform.Response.ResponseUtils;
import com.graduation.smartparkingplatform.Service.UserService;
import com.graduation.smartparkingplatform.Utils.IpUtil;
import com.graduation.smartparkingplatform.Utils.JwtUtils;
import com.graduation.smartparkingplatform.Utils.ValidateCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/user")
public class LoginController {
  @Autowired CaptchaRepository captcharepository;
  @Autowired UserService userService;
  @Autowired RedisTemplate redisTemplate;

  @GetMapping("/getCaptchaBase64")
  public Object getCaptchaBase64(HttpServletRequest request, HttpServletResponse response) {
    String ipAddress = IpUtil.getIpAddr(request);
    log.info("IP：" + ipAddress + " get captchaBase64");
    try {
      // 创建返回对象类
      Map<String, String> result = new HashMap<>();
      response.setContentType("image/png");
      response.setHeader("Cache-Control", "no-cache");
      response.setHeader("Expire", "0");
      response.setHeader("Pragma", "no-cache");
      ValidateCodeUtil validateCode = new ValidateCodeUtil();
      // 返回base64结果hashMap对象
      Map<String, String> base64_Object = validateCode.getRandomCodeBase64(response);
      String randomStr = String.valueOf(base64_Object.get("randomStr"));
      String base64String = String.valueOf(base64_Object.get("base64String"));

      // 生成随机验证码ID
      String str = "abcdefghijklmnopqr0123456789";
      Random random = new Random();
      StringBuilder id = new StringBuilder();
      for (int i = 0; i < str.length(); i++) {
        int number = random.nextInt(str.length());
        id.append(str.charAt(number));
      }

      // 通过hashmap存入dedis中,过期时间定位90seconds
      redisTemplate.opsForValue().set("id_" + id.toString(), randomStr, 90, TimeUnit.SECONDS);
      result.put("url", "data:image/png;base64," + base64String);
      result.put("id", id.toString());
      result.put("message", "success");
      //      System.out.println("结果：" + result.get("url"));
      return result; // 返回base64图片结果
    } catch (Exception e) {
      log.error("captchaBase64 error-" + e);
      return ResponseUtils.buildBUSSINESS_ERROR(e); // 返回系统错误
    }
  }

  @PostMapping("/login")
  public Response toLogin(
      @RequestParam("username") String username,
      @RequestParam("password") String password,
      @RequestParam("code") String code,
      @RequestParam("id") String id,
      HttpServletRequest request) {
    try {
      // 用户发出请求的code
      String receivedCode = code.toLowerCase();
      // 获取请求IP地址
      String ipAddress = IpUtil.getIpAddr(request);
      // 获取设备信息
      String agent = request.getHeader("User-Agent");
      // 根据IP地址去redis寻找验证码
      Boolean hasValue = redisTemplate.hasKey("id_" + id);
      if (hasValue) {
        String result = (String) redisTemplate.opsForValue().get("id_" + id);
        String redisCode = result.toLowerCase();
        if (receivedCode.equals(redisCode)) {
          User user = userService.toLogin(username, password);
          if (user != null) {
            Integer userId = user.getUser_id();
            Boolean status = user.getStatus();
            Boolean admin = user.getAdmin();
            String nickname = user.getNickname();
            if (status) {
              Boolean loginLog = userService.visitorLog(userId, username, ipAddress, agent);
              Map<String, String> map = new HashMap<>();
              map.put("username", username);
              map.put("status", status.toString());
              map.put("admin", admin.toString());
              String token = JwtUtils.getToken(map);
              HashMap<String, String> resultMap = new HashMap<>(1);
              resultMap.put("token", token);
              resultMap.put("userId", userId.toString());
              resultMap.put("nickname", nickname);
              resultMap.put("admin", admin.toString());
              log.info("username:" + username + " in ip:" + ipAddress + " login");
              return ResponseUtils.buildAUTH_SUCCESS(resultMap); // 登录成功返回token
            }
            return ResponseUtils.buildLOGIN_ERROR(); // 无权限登录
          }
          return ResponseUtils.buildIDENTIT_ERROR(); // 返回账户名或密码错误
        } else {
          Boolean deleteRedis = redisTemplate.delete("id_" + code);
          return ResponseUtils.buildVERIFY_CODE_ERROR(); // 返回验证码错误
        }
      }
      return ResponseUtils.buildVERIFY_CODE_EXPIRE(); // 返回验证码过期
    } catch (Exception e) {
      log.error("login error-" + e);
      return ResponseUtils.buildBUSSINESS_ERROR(e); // 返回系统错误
    }
  }
}
